<?php


namespace Tbf\Bundle\RouteBundle;


use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class RouteListener implements EventSubscriberInterface{
    protected $config;
    public function __construct(RouteConfig $config){
        $this->config = $config;
    }
    public function onKernelRequest(GetResponseEvent $event){
        //检测_controller以便放过symfony错误处理程序
        if ($event->getRequest()->attributes->has('_controller')){
            return;
        }
        $request = $event->getRequest();
        foreach($this->config->getExcludeRoutes() as $exclude){
            if ($exclude->isExclude($request)){
                return;
            }
        }
        foreach($this->config->getMatchRoutes() as $matcher){
            $resp = $matcher->match($request);
            if ($resp===null){
                continue;
            }
            $event->setResponse($resp);
            $event->stopPropagation();
            return ;
        }
        return;
    }
    public static function getSubscribedEvents(){
        return array(
            KernelEvents::REQUEST=>array('onKernelRequest',100),
        );
    }
}